import { Component } from 'react'
import { View, Button, Text, Canvas } from '@tarojs/components'
import { observer, inject } from 'mobx-react'
import Taro from '@tarojs/taro'

import './index.less'

type PageStateProps = {
  store: {
  }
}

interface Index {
  props: PageStateProps;
}

@inject('store')
@observer
class Index extends Component {
  componentWillMount () { }

  componentDidMount () { }

  componentWillUnmount () { }

  componentDidShow () { }

  componentDidHide () { }

  onSaveImg = async () => {
    const context = Taro.createCanvasContext('firstCanvas');
    let total = 0
    this.drawHeaderImage(context)
  }

  drawHeaderImage = async (context) => {
    // const {
    //   coverPath = {}
    // } = this
    context.save()
    const imageInfo = await Taro.getImageInfo({
      src: 'http://qnm.hunliji.com/o_1am8g8532pgd1gbn1chk14gd1g3f11.jpg'
    })
    const { path, height, width } = imageInfo;
    context.drawImage(path, 0, 0, 350, 750);
    context.restore()
    context.save()
    console.log(imageInfo, 88889999)

    await new Promise((resolve) => {
      context.draw(false, () => {
        setTimeout(() => {
          resolve()
        }, 300)
      })
    }) 

    console.log(1111111)

    const { tempFilePath } = await Taro.canvasToTempFilePath({
      x: 0,
      y: 0,
      width: 1000,
      height: 1000,
      destWidth: 1000,
      destHeight: 1000,
      quality: 1,
      canvasId: 'firstCanvas'
    })

    console.log(222222222, tempFilePath)


    Taro.saveImageToPhotosAlbum({
      filePath: tempFilePath,
      success() {
        // Taro.showToast({title: '已保存到相册', duration: 2000 })
        Taro.showModal({
          title: '保存海报成功',
          content: '海报已保存到手机相册，请前往微信进行分享',
          showCancel: false,
          confirmText: '确定'
        })
      },
      fail() {
        Taro.showToast({
          title: '保存失败',
          icon: 'none'
        })
      }
    })
  }

  render () {
    console.log(this.props, 22222222)
    return (
      <View className='index' onClick={this.onSaveImg}>
        <Canvas
          style={{
            height: `100%`,
            width: '100%',
            background: '#FFF',
            position: 'fixed',
            // top: '-200%',
            // left: '-3000px'
          }}
          canvas-id='firstCanvas'
        >
        </Canvas>
        {/* <Text onClick={this.onSaveImg}>保存图片</Text> */}
      </View>
    )
  }
}

export default Index
